<template>
  <div class="city-search">
    <div class="search flex flex-col justify-center">
      <van-search v-model="keyword" shape="round" placeholder="请输入城市名称或拼音" />
    </div>
    <better-scroll v-show="keyword" class="search-list" ref="scroll" :data="lists" :pull-up="false" :pull-down="false">
      <ul>
        <li class="search-item border-b" v-for="(item, index) of lists" :key="index" @click="handleCity(item.name)">
          {{ item.name }}
        </li>
        <li v-show="hasList" class="search-item text-center text-gray-500">没有匹配数据</li>
      </ul>
    </better-scroll>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import BetterScroll from '@/components/BetterScroll/BetterScroll.vue'

export default {
  name: 'CitySearch',
  components: {
    BetterScroll,
  },
  props: {
    list: [Object, Array],
  },
  data() {
    return {
      keyword: '',
      lists: [],
      timer: null,
    }
  },
  computed: {
    hasList() {
      return !this.lists.length
    },
  },
  watch: {
    keyword() {
      this.timer && clearTimeout(this.timer)
      if (!this.keyword) return (this.lists = [])
      this.timer = setTimeout(() => {
        const data = []
        for (let i in this.list) {
          this.list[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              data.push(value)
            }
          })
        }
        this.lists = data
      }, 300)
    },
  },
  methods: {
    ...mapActions(['changeCity']),
    // 选择城市
    handleCity(city) {
      // this.$store.dispatch('changeCity', city)
      this.changeCity(city)
      this.lists = []
      this.keyword = ''
      this.$router.push({ path: '/' })
    },
  },
}
</script>

<style lang="scss" scoped>
.city-search {
  .search {
    .van-search {
      height: 0.4rem;
      width: 100%;
    }
  }
  .search-list {
    position: absolute;
    top: 0.83rem;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    background: #eee;
    // 溢出隐藏内容
    overflow: hidden;
    .search-item {
      line-height: 0.32rem;
      padding-left: 0.1rem;
      background: #fff;
      color: #666;
    }
  }
}
</style>
